package jp.ne.hatena.d.digitalsoul.warikan.repositories.impl

import scala.collection.JavaConversions._

import org.apache.cassandra.thrift._

import org.apache.thrift.protocol.TBinaryProtocol
import org.apache.thrift.protocol.TProtocol
import org.apache.thrift.transport.TSocket
import org.apache.thrift.transport.TTransport

import jp.ne.hatena.d.digitalsoul.warikan.models._
import jp.ne.hatena.d.digitalsoul.warikan.cassandra._
import CassandraRange._

class RoleRepositoryImpl {
				
	def forAll:List[Role] = {
		val keySlices = getRoleColumns
		createRoleList(keySlices)
	}
	
	
	private def getRoleColumns:java.util.List[KeySlice] = {

		val transport:TTransport = new TSocket("localhost", 9160)
		val protocol:TProtocol = new TBinaryProtocol(transport)
		val client:Cassandra.Client = new Cassandra.Client(protocol)
		transport.open
		
		try {
		
			val columnParent:ColumnParent = new ColumnParent("Role")
		
			val keySlices:java.util.List[KeySlice] = client.get_range_slices("warikan", columnParent, sliceRangeAll, keyRangeAll, ConsistencyLevel.ONE)
		
			return keySlices
		
		} finally { 
			transport.close
		}
	}
	
	private def createRoleList(keySlices:java.util.List[KeySlice]):List[Role] = {
		
		var roles = List[Role]()
		keySlices.foreach { keySlice =>
			val role = convertToRole(keySlice)
			roles ::= role
		}
		
		roles		
	}
	
	private def convertToRole(keySlice:KeySlice):Role = {
		val roleCoSs = keySlice.columns
		var roleName:String = null
		roleCoSs.foreach { roleCoS =>
			val column = roleCoS.column
			new String(column.name, "utf-8") match {
				case "roleName" => roleName = new String(column.value, "utf-8")
			}
		}
		new Role(roleName)
	}

}